package com.zlm.tools.validation;

import org.quartz.xml.ValidationException;

import java.util.ArrayList;
import java.util.List;

/**
 * {@code 校验链}
 *
 * @author zlm
 * @since 2025/5/30
 */
public class ValidatorChain {

    private final List<ValidatorHandler> handlers = new ArrayList<>();


    /**
     * 校验
     *
     * @param value
     */
    public void vaildate(String filedName,Object value) {
        ValidatorContext context = new ValidatorContext(value);
        while (true){
            int index = context.currentIndex();
            if(index == handlers.size()){
                //校验器全部校验完毕
                break;
            }
            ValidatorHandler  handler = handlers.get(index);
            handler.validate(filedName,context.getValue(), context);
            if(index == context.currentIndex()){
                //校验未调用doNext方法，说明校验器没有校验通过，则停止校验
                break;
            }
        }

        context.throwExceptionIfNecessary();

    }

    /**
     * 添加校验器
     *
     * @param handler
     */
    public void addLastHandler(ValidatorHandler handler) {
        this.handlers.add(handler);
    }
}

